import { useEffect, useState } from "react";
import { Form, Input, Button, Checkbox, Card, Tabs } from "antd";
import { UserOutlined, LockOutlined, MailOutlined } from "@ant-design/icons";
import { useNavigate } from "react-router-dom";
import type { LoginParams, RegisterParams } from "./api-types";
import {
  getCaptchaApi,
  postCreateUserApi,
  postLoginApi,
  postverifyCaptchaApi,
} from "../../api/user";
import type { TabsProps } from "antd";
import type { LoginAndCaptchaProps } from "./types";
import { errorMsg, successMsg } from "../../utils/message";
import { useDispatch } from "react-redux";
import { changeToken } from "../../store/user";

const LoginPage = () => {
  
  const onChange = (key: string) => {
    setKey(key);
  };

  const [captchaToken, setCaptchaToken] = useState<string>("");
  const [svg, setSvg] = useState<string>("");
  const [key, setKey] = useState<string>("1");

  // 共享的验证码生成方法
  const generateCaptcha = async () => {
    try {
      const captcha = await getCaptchaApi();
      setCaptchaToken(captcha.token);
      setSvg(captcha.svg);
      return captcha.token;
    } catch (error) {
      console.error("API请求失败:", error);
      throw error; // 抛出错误以便子组件处理
    }
  };

  const items: TabsProps["items"] = [
    {
      key: "1",
      label: "登录",
      children: (
        <Login
          svg={svg}
          generateCaptcha={generateCaptcha}
          captchaToken={captchaToken}
        ></Login>
      ),
    },
    {
      key: "2",
      label: "注册",
      children: (
        <Captcha
          svg={svg}
          generateCaptcha={generateCaptcha}
          captchaToken={captchaToken}
          setKeyValue={(value) => {
            setKey(value);
          }}
        ></Captcha>
      ),
    },
  ];

  return (
    <div
      style={{
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
        minHeight: "100vh",
        background: "#f0f2f5",
      }}
    >
      <Card style={{ width: 400 }}>
        <Tabs
          destroyOnHidden
          activeKey={key}
          items={items}
          onChange={onChange}
        />
      </Card>
    </div>
  );
};

function Login({ svg, captchaToken, generateCaptcha }: LoginAndCaptchaProps) {
  const [loading, setLoading] = useState(false);
  const [captchaInput, setCaptchaInput] = useState("");
  const navigate = useNavigate();
  const dispatch = useDispatch();

  // 初始化验证码
  useEffect(() => {
    generateCaptcha();
  }, []);

  // 登录表单提交
  const onLoginFinish = async (values: LoginParams) => {
    await postverifyCaptchaApi({
      code: captchaInput,
      captchaId: captchaToken,
    });
    setLoading(true);
    try {
      const response = await postLoginApi({
        username: values.username,
        password: values.password,
      });
      successMsg("登录成功");
      dispatch(changeToken(response));
      localStorage.setItem("token", response.token);
      navigate("/", { replace: true });
    } catch (error) {
      console.error(error + "登录失败");
      generateCaptcha();
    } finally {
      setLoading(false);
    }
  };

  return (
    <Form
      name="login"
      initialValues={{ remember: true }}
      onFinish={onLoginFinish}
    >
      <Form.Item
        name="username"
        rules={[{ required: true, message: "请输入用户名!" }]}
      >
        <Input prefix={<UserOutlined />} placeholder="用户名" />
      </Form.Item>

      <Form.Item
        name="password"
        rules={[{ required: true, message: "请输入密码!" }]}
      >
        <Input.Password prefix={<LockOutlined />} type="" placeholder="密码" />
      </Form.Item>

      <Form.Item>
        <div
          style={{ display: "flex", alignItems: "center" }}
        >
          <Input
            prefix={<LockOutlined />}
            placeholder="验证码"
            value={captchaInput}
            onChange={(e) => setCaptchaInput(e.target.value)}
            style={{ width: "60%", marginRight: 8 }}
          />
          <div
            dangerouslySetInnerHTML={{ __html: svg }}
            onClick={generateCaptcha}
          ></div>
        </div>
      </Form.Item>

      <Form.Item>
        <Form.Item name="remember" valuePropName="checked" noStyle>
          <Checkbox>记住我</Checkbox>
        </Form.Item>
        <a style={{ float: "right" }} href="/forgot-password">
          忘记密码
        </a>
      </Form.Item>

      <Form.Item>
        <Button type="primary" htmlType="submit" loading={loading} block>
          登录
        </Button>
      </Form.Item>
    </Form>
  );
}

function Captcha({
  svg,
  captchaToken,
  generateCaptcha,
  setKeyValue,
}: LoginAndCaptchaProps) {
  const [captchaInput, setCaptchaInput] = useState("");
  const [loading, setLoading] = useState(false);

  // 初始化验证码
  useEffect(() => {
    generateCaptcha();
  }, []);

  // 注册表单提交
  const onRegisterFinish = async (values: RegisterParams) => {
    const res = await postverifyCaptchaApi({
      code: captchaInput,
      captchaId: captchaToken,
    });
    if (!res) {
      generateCaptcha();
    }
    setLoading(true);
    try {
      await postCreateUserApi({
        username: values.username,
        password: values.password,
        email: values.email,
      });
      setKeyValue?.("1");
      successMsg("注册成功");
    } catch (error) {
      errorMsg(error + "注册失败");
      generateCaptcha();
    } finally {
      setLoading(false);
    }
  };
  return (
    <Form name="register" onFinish={onRegisterFinish}>
      <Form.Item
        name="username"
        rules={[{ required: true, message: "请输入用户名!" }]}
      >
        <Input prefix={<UserOutlined />} placeholder="用户名" />
      </Form.Item>

      <Form.Item
        name="email"
        rules={[
          { required: true, message: "请输入邮箱!" },
          { type: "email", message: "请输入有效的邮箱地址!" },
        ]}
      >
        <Input
          autoComplete="email"
          prefix={<MailOutlined />}
          placeholder="邮箱"
        />
      </Form.Item>

      <Form.Item
        name="password"
        rules={[
          { required: true, message: "请输入密码!" },
          { min: 6, message: "密码至少6个字符!" },
        ]}
      >
        <Input.Password
          autoComplete="password"
          prefix={<LockOutlined />}
          placeholder="密码"
        />
      </Form.Item>

      <Form.Item
        name="confirmPassword"
        dependencies={["password"]}
        rules={[
          { required: true, message: "请确认密码!" },
          ({ getFieldValue }) => ({
            validator(_, value) {
              if (!value || getFieldValue("password") === value) {
                return Promise.resolve();
              }
              return Promise.reject("两次输入的密码不一致!");
            },
          }),
        ]}
      >
        <Input.Password
          autoComplete="new-password"
          prefix={<LockOutlined />}
          placeholder="确认密码"
        />
      </Form.Item>

      <Form.Item>
        <div style={{ display: "flex", alignItems: "center" }}>
          <Input
            prefix={<LockOutlined />}
            placeholder="验证码"
            value={captchaInput}
            onChange={(e) => setCaptchaInput(e.target.value)}
            style={{ width: "60%", marginRight: 8 }}
          />
          <div
            dangerouslySetInnerHTML={{ __html: svg }}
            onClick={generateCaptcha}
          ></div>
        </div>
      </Form.Item>

      <Form.Item>
        <Button type="primary" htmlType="submit" loading={loading} block>
          注册
        </Button>
      </Form.Item>
    </Form>
  );
}

export default LoginPage;
